<?php

namespace app\user\controller;

use app\common\base\_Db;
use app\common\controller\CommonController;
use app\common\controller\ResponseJson;
use think\Exception;
use app\common\entity\RequestEntity;
use think\Db;

class Menu extends CommonController
{
    /*
     * 菜单
     */
    public function Index()
    {
        $RoleId = new RequestEntity('RoleId', '角色id', false, 32);
//        $RoleId = (int)1;
        return ResponseJson::Json($this->MenuResult($RoleId->text));
    }
    /**
     * @param $RoleId
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function MenuResult($RoleId)
    {
        if ($RoleId == 1) {
            $res = Db::name('menu')
                ->field(
                    [
                        'pri_id',
                        'pri_name',
                        'pri_pid',
                        'url',
                        'imgL',
                        'imgN',
                    ]
                )
                ->where('pri_status = 1')
                ->select();
            $res = $this->AddHttpPath($res);
            return ResponseJson::Json($this->GetTreeData($res,0));
        } else {
            $where = 'r.role_id = ' . $RoleId;
            $res = Db::name('menu m')
                ->field('m.pri_name ,m.pri_id ,m.pri_pid,m.url,m.imgL,m.imgN')
                ->join('role_menu r', 'r.pri_id = m.pri_id')
                ->where($where . ' and m.pri_status = 1')
                ->select();
            $res = $this->AddHttpPath($res);
            return ResponseJson::Json($this->GetTreeData($res,0));
        }
    }
    public function AllMenu(){
        $res = Db::name('menu')
            ->field(
                [
                    'pri_id',
                    'pri_name',
                    'pri_pid',
                    'url',
                    'imgL',
                    'imgN',
                ]
            )
            ->where('pri_pid != 0 and pri_status = 1')
            ->select();
        $res = $this->AddHttpPath($res);
        return ResponseJson::Json($res);
    }

    public function AddHttpPath($res){
        foreach ($res as $key => $value){
           $res[$key]['imgL'] = HttpPath.$value['imgL'];
           $res[$key]['imgN'] = HttpPath.$value['imgN'];
        }
        return $res;
    }
    public function updateMenu()
    {

    }

    /**
     * 查询角色
     */
    public function ListRole()
    {
        $param_page = $get_page = input('Page', 1);
        $param_pagesize =  10;
        $get_keyword = new RequestEntity('search_key', '搜索内容', false, 0);
        $where = '1=1';
        if(!empty($get_keyword->text)){
            $where .= ' and role_name  like "' . $get_keyword->text.'%"';
        }
        $res = Db::name('role')
            ->field(
                [
                    'role_id'=>'Id',
                    'role_name' => 'Name',
                    'role_remark' => 'Remark',
                    'role_isvalid' => 'Isvalid',
                    'oper_id'=>'Operator'
                ]
            )
            ->where($where)
            ->limit(($param_page - 1) * $param_pagesize, $param_pagesize)
            ->select();
        foreach ( $res as $key => $value){
            if($res[$key]['Operator']){//操作者id 转换姓名
                $res[$key]['Operator']=$this->GetUserName($res[$key]['Operator']);
            }
            /*if ($res[$key]['Isvalid'] == 1){
                $res[$key]['Isvalid'] = "否";
            }elseif ($res[$key]['Isvalid'] == 2){
                $res[$key]['Isvalid'] = "是";
            };*/
            $res[$key]['Order'] = $key + 1;
        }
        $int_total_count = count(Db::name('role')->where($where)->select());
        $data['tableData']=$res;
        $data['TotalCount'] = $int_total_count;
        $data['Page'] = (int)$param_page;
        $data['PageSize'] = (int)$param_pagesize;
        _Db::ResponseJson($data);
    }
    public function GetUserName($id){
        $res = Db::name('staff')
            ->field('nick_name')
            ->where('staff_id ='.$id)
            ->find();
        return $res['nick_name'];
    }
    /**
     * 查找当前权限
     * 用于角色修改
     */
    public function FindMenu()
    {
        $RoleId = new RequestEntity('RoleId', '角色名称', false, 32);
        $res['Data'] = Db::name('menu m')
            ->field('m.pri_name ,m.pri_id ,m.pri_pid,m.imgL,m.imgN')
            ->join('role_menu r', 'r.pri_id = m.pri_id')
            ->join('role e','r.role_id = e.role_id')
            ->where('r.role_id = "' . $RoleId->text.'"and pri_pid !=0')
            ->select();
        $data = Db::name('role')
            ->field(['role_name'=>'Name',
                      'role_id'=>'Id',
                      'role_remark'=>'Remark',
                      'role_isvalid'=>'Isvalid'
                    ])
            ->where('role_id ='. $RoleId->text)
            ->find();
        $res['role'] = $data;
        return ResponseJson::Json($res);

    }
    public function RoleInfo(){
        $RoleId = new RequestEntity('RoleId', '角色名称', false, 32);
        $res = Db::name('role')
            ->field(
                [
                    'role_id'=>'Id',
                    'role_name' => 'Name',
                    'role_remark' => 'Remark',
                    'role_isvalid' => 'Isvalid',
                    'oper_id'=>'Operator'
                ]
            )
            ->where('role_id ='.$RoleId->text)
            ->find();
        return ResponseJson::Json($res);
    }

    public function FindAllMenu()
    {
        $res = Db::name('menu')
            ->field('pri_name ,pri_id ,pri_pid')
            ->select();
        return ResponseJson::Json($this->GetTreeData($res, 0));
    }

    public function GetTreeData($Data, $Pid)
    {
        $tree = [];
        foreach ($Data as $k => $v) {
            if ($v['pri_pid'] == $Pid) {        //父亲找到儿子
                $v['navSecList'] = $this->GetTreeData($Data, $v['pri_id']);
                $tree[] = $v;
            }
        }
        return $tree;
    }

    /**
     * 添加角色
     */
    public function AddRole()
    {
        $RoleName = new RequestEntity('RoleName', '角色名称', false, 32);
        $RoleRemark = new RequestEntity('RoleRemark', '角色描述', false, 32);
        //$IsValid = new RequestEntity('IsValid', '是否有效', false, 32);
        $CreatId = new RequestEntity('CreatId', '操作人', false, 32);
        $RoleIdArray = new RequestEntity('RoleIdArray', '操作人', false, 32);
        //$RoleIdArray = Request::instance()->param()['RoleIdArray'];
        $rsult=explode(',',$RoleIdArray->text);
        $data = [
            'role_name' => $RoleName->text,
            'role_remark' => $RoleRemark->text,
            'oper_date' => date("Y-m-d H:i:s",time()),
            'oper_id' => $CreatId->text,
        ];
        //添加数据
        if ($Id = Db::name('role')->insertGetId($data)) {
            //添加菜单关联数据
            $re_data = [];
            foreach ($rsult as $key => $value) {
                if (!empty($value)){
                    $res = Db::name('menu')->field('pri_name ,pri_id ,pri_pid')->where('pri_id = '.$value)->find();
                    if (!empty($res)){
                        $res_role = Db::name('role_menu')->field('role_id,pri_id')->where('pri_id = '.$res['pri_pid'].' and role_id = '.$Id)->select();
                        if (empty($res_role)){
                            $re_data['role_id'] = $Id;
                            $re_data['pri_id'] = $res['pri_pid'];
                            $re_data['oper_date'] = date("Y-m-d H:i:s",time());
                            $re_data['oper_id'] = $CreatId->text;
                            Db::name('role_menu')->insert($re_data);
                        }
                    }
                }
                $re_data['role_id'] = $Id;
                $re_data['pri_id'] = $value;
                $re_data['oper_date'] = date("Y-m-d H:i:s",time());
                $re_data['oper_id'] = $CreatId->text;
                Db::name('role_menu')->insert($re_data);
            }
            _Db::log($CreatId->text,1,'角色添加');
        }
        $this->ListRole();
    }

    /**
     * 修改角色
     */
    public function ModifyRole()
    {
        $RoleId = new RequestEntity('RoleId', 'ID', false, 32);
        $RoleName = new RequestEntity('RoleName', '角色名称', false, 32);
        $RoleRemark = new RequestEntity('RoleRemark', '角色描述', false, 32);
        //$IsValid = new RequestEntity('IsValid', '是否有效', false, 32);
        $CreatId = new RequestEntity('CreatId', '操作人', false, 32);
        $RoleIdArray = new RequestEntity('RoleIdArray', '操作人', false, 32);
        //$RoleIdArray = Request::instance()->param()['RoleIdArray'];
        $rsult=explode(',',$RoleIdArray->text);
        $data = [
            'role_name' => $RoleName->text,
            'role_remark' => $RoleRemark->text,
            'oper_date' => date('Y-M-D H:i:s', time()),
            'oper_id' => $CreatId->text
        ];
        Db::name('role')
            ->where('role_id =' . $RoleId->text)
            ->update($data);

        try {
            Db::name('role_menu')
                ->where('role_id =' . $RoleId->text)
                ->delete();
        } catch (Exception $e) {
            return ResponseJson::Json($e);
        }
        //添加菜单关联数据
        $re_data = [];
        foreach ($rsult as $key => $value) {
            $re_data['role_id'] = $RoleId->text;
            $re_data['pri_id'] = $value;
            $re_data['oper_date'] = date("Y-m-d H:i:s",time());
            $re_data['oper_id'] = $CreatId->text;
            Db::name('role_menu')->insert($re_data);
        }
        _Db::log($CreatId->text,3,'角色修改');
        $this->Item($RoleId->text);

    }
    public function Item($id)
    {
        $res = Db::name('role')
            ->field(
                [
                    'role_id'=>'Id',
                    'role_name' => 'Name',
                    'role_remark' => 'Remark',
                    //'role_isvalid' => 'Isvalid',
                    'oper_id'=>'Operator'
                ]
            )
            ->where('role_id ='.$id)
            ->find();

        if($res['Operator']){//操作者id 转换姓名
            $res['Operator']=$this->GetUserName($res['Operator']);
        }
        _Db::ResponseJson($res);
    }
    /*
     * 角色删除
     */
    public function RemoveRole()
    {
        $RoleId = new RequestEntity('RoleId', '角色名称', false, 32);
        $post_creatid = new RequestEntity('CreatId', '操作人', false, 32);
        $res = Db::name('staff_role')
            ->field('staff_id')
            ->where('role_id ='.$RoleId->text)
            ->select();
        if ($RoleId->text == 1){
            _Db::Response(3,'管理员不能删除');
        }elseif(!empty($res)){
            _Db::Response(3,'该角色绑定人员不能删除');
        }else{
            if (Db::name('role')->where('role_id =' . $RoleId->text)->delete())
            {
                Db::name('role_menu')->where('role_id =' . $RoleId->text)->delete();
                Db::table('staff_role')->where('role_id =' . $RoleId->text);
            }
            _Db::log($post_creatid->text,2,'角色删除');
            $this->ListRole();
        }
    }
    //审核
    public function SwitchModity(){
        //获取请求参数
        $request_data = [
            $post_itemid = new RequestEntity('RoleId', 'ID', true, 10),
            $post_value = new RequestEntity('Value', '值', true, 10),
            $post_creatid = new RequestEntity('CreatId','操作人Id', false, 30),
        ];
        //表单内容验证
        _Db::Validates($request_data);
        if ($post_value->text == 3){
            $type = 7;
            $content = '人员审核';
            $param_field = [
                'regist'    => 3,
                'oper_id'   => $post_creatid->text,
                'oper_date' => date("Y-m-d H:i:s",time()),
            ];
        }elseif ($post_value->text == 4){
            $type = 8;
            $content = '审核驳回';
            $param_field = [
                'regist'    => 4,
                'oper_id'   => $post_creatid->text,
                'oper_date' => date("Y-m-d H:i:s",time()),
            ];
        }
        //设置条件
        $param_where = [
            'role_id' => $post_itemid->text,
        ];
        $result = Db::table('role')
            ->where($param_where)
            ->update($param_field);
        if ($result){
            _Db::log($post_creatid->text,$type,$content);
            $this->Item($post_itemid->text);
        }
    }
}